import json

from flask import Flask, request, Response
from flask import render_template
from requests import Session, Request

app = Flask(__name__)


# 页面展示
@app.route('/')
def home():
    return render_template('requesttools.html')


# 处理http请求
@app.route("/http", methods=['post'])
def http_request():
    url = request.form['url']
    method = request.form['method']
    headers = parse_headers(request.form['headers'])
    params = request.form['params']
    args = parse_params(params)

    return send(url, method, headers, args)


# 统一发起http请求
def send(url, method, headers, data):
    s = Session()
    req = Request(method, url,
                  data=data,
                  params=data,
                  headers=headers
                  )
    prepped = req.prepare()
    resp = s.send(prepped)
    try:
        res = {"header": "{0}".format(resp.headers), "body": "{0}".format(resp.content.decode(encoding='utf-8'))}
        return Response(json.dumps(res), mimetype='application/json')
    except:
        res = {"header": "{0}".format(resp.headers), "body": "{0}".format(resp.content)}
        return Response(json.dumps(res), mimetype='application/json')


# 处理请求参数转换成字典
def parse_params(params):
    args = {}
    if params:
        sps = params.split('&')
        for s in sps:
            p = s.split("=")
            print(p[0], "=", p[1])
            args[p[0]] = p[1]

    return args


# 处理请求头信息转换成字典
def parse_headers(headers):
    args = {}
    if headers:
        sps = headers.split(',')
        for s in sps:
            p = s.split(":")
            print(p[0], "=", p[1])
            args[p[0]] = p[1]

    return args


# 用于测试参数的接收和头信息的接收
@app.route('/test', methods=['get', 'post'])
def test():
    if request.method == 'GET':
        a = request.args.get('a', '')
        b = request.args.get('b', '')
        token = request.headers.get('token')
        return '测试get请求,参数 a={0},b={1},头:token={2}'.format(a, b, token)

    a = request.form['a']
    b = request.form['b']
    token = request.headers.get('token')

    return '测试post请求,参数 a={0},b={1},头:token={2}'.format(a, b, token)


if __name__ == '__main__':
    app.run()
